package com.tanhua.sso.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

/**
 * 用于读取RSA所存储的公钥和私钥的文件 如果文件不存在则生成文件
 */
@Getter
@Service
public class RSAService {

    private String publicKeyStr;
    private String privateKeyStr;
    @Value("${tanhua.rsa.dir}")
    private String rsaFileDir;

    @PostConstruct
    public void init() {
        File publicKeyFile = new File(rsaFileDir + File.separator + "rsa.pub");
        if (FileUtil.exist(publicKeyFile)) {
            this.publicKeyStr = FileUtil.readString(publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        File privateKeyFile = new File(rsaFileDir + File.separator + "rsa");
        if (FileUtil.exist(privateKeyFile)) {
            this.privateKeyStr = FileUtil.readString(privateKeyFile, CharsetUtil.CHARSET_UTF_8);
        }

        if (StrUtil.isAllNotEmpty(this.privateKeyStr, this.publicKeyStr)) {
            return;
        }
        RSA rsa = new RSA();
        /*
         * 将String写入文件，覆盖模式
         *
         * @param content 写入的内容
         * @param path    文件路径
         * @param charset 字符集
         */
        FileUtil.writeString(rsa.getPublicKeyBase64(), publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        FileUtil.writeString(rsa.getPrivateKeyBase64(), privateKeyFile, CharsetUtil.CHARSET_UTF_8);
        this.publicKeyStr = rsa.getPublicKeyBase64();
        this.privateKeyStr = rsa.getPrivateKeyBase64();
    }
}
